import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import {
  getStorage,
} from '@/utils/auth'

import store from '@/store/index'
import NProgress from 'nprogress'
// 定义登录路由
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: "login",
    component: () => import("@/views/login/Index.vue")
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//路由前置守卫
router.beforeEach((to: any, from: any, next: any) => {
  NProgress.start()
  // 判断是否有token 否则去登录页 ，暂时不需要token
  // if (!getStorage('token') || to.path === './login') {
  if (!getStorage('token') && to.path === './login') {
    return next({ path: "./login" })
  }
  // 判断是否已经添加路由，否则组装路由文件
  if (!store.state.routerMenu.permissionList) {
    store.dispatch("routerMenu/FETCH_PERMISSION").then(() => {
      next(to.path)
    })
  } else {
    next()
  }
})

//路由后置守卫
router.afterEach((to: any, from: any, next: any) => {
  NProgress.done()
  try {
    if (to.meta.name) {
      document.title = to.meta.name
    }
  } catch (error) {
    console.log(error);
  }
  const routerList = to.matched;
  // 设置面包屑
  store.commit("routerMenu/setCrumbList", routerList)
  store.commit("routerMenu/SET_CURRENT_MENU", to.name)

})

export default router